<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\Config;
use Illuminate\Support\Facades\Input;
use App\Http\Requests\Admin\ConfigRequest;
use App\Services\OSS;

class ConfigController extends Controller
{   
    // 文件上传
    public function upload(Request $request)
    {
//        获取文件对象
        $file = Input::file('field');
//        判断文件是否有效
        if($file->isValid()){
            $entension = $file->getClientOriginalExtension();//上传文件的后缀名
            $newName = date('YmdHis').mt_rand(1000,9999).'.'.$entension;
            //$path = $file->move(public_path().'/uploads/config',$newName);
            $filepath = 'uploads/config/'.$newName;
            // 获取图片在临时文件中的地址
       
            $pic = $file->getRealPath();

            //阿里 OSS 图片上传
            $result = OSS::upload($filepath, $pic);

            return  $filepath;
        }
    }

    //    将数据库的config表中的网站配置数据写入config目录下的webconfig文件
    public function putFile()
    {
//        1 从config表中取出网站配置数组
         $conf =  Config::lists('conf_content','conf_name')->toArray();
        // dd($conf);
//         将数组变量变成字符串格式的数组
       $arr = '<?php return  '.var_export($conf,true).';';

//       2 将数据写入config目录下的webconfig文件
//        参数一 要写入的文件的路径
//        参数二 要写入的文件的内容
        file_put_contents(base_path().'/config/webconfig.php',$arr);
    }

//    批量更新内容
    public function changContent(Request $request)
    {   
        // $input = $request->only('conf_id','conf_content','field_type');
        
            
        // dd($input);
        
        // dd(1);
            $input = $request->only('conf_id','conf_content');
    //        dd($input);
            $conf_id = $input['conf_id'];
            $conf_content = $input['conf_content'];
            foreach ($conf_id as $k=>$v) {
    //            通过$v作为id，获取到要修改那那条记录
               $conf =  Config::find($v);
               $conf->conf_content = $input['conf_content'][$k];
               $res = $conf->save();
            }
            $this->putFile();
            // $this->putFile();
            if($res){
                return redirect('admin/config')->with('success','修改成功');
            }else{
                return back()->with('errors','修改失败');
            }
        

    }
   


    /**
     * 网站配置列表  
     * 遍历数据  组合数据 
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
       //判断field_type字段，来决定conf_content的显示样式

        $data = Config::all();
        foreach($data as $k=>$v){
            switch ($v['field_type']){
                case 'input':
//                    <input type="text" name="conf_name">
                 $v['conf_contents'] = '<input class="lg" type="text" name="conf_content[]" value="'.$v['conf_content'].'">';

                    break;
                case "textarea":
//                    <textarea name="conf_tips"></textarea>
                    $v['conf_contents'] = '<textarea name="conf_content[]">'.$v['conf_content'].'</textarea>';
                    break;

                case "img":
//                    <textarea name="conf_tips"></textarea>

                    $v['conf_contents'] = '<img src="http://lamp187mall.oss-cn-beijing.aliyuncs.com/'.$v['conf_content'].'" alt="图片" width="100px" ><input type="hidden" name="conf_content[]" value="'.$v->conf_content.'">';

                    break;
                case 'radio':
//                    1|开启,0|关闭
//                <input type="radio" name="conf_content[]" value="1">开启　
//                <input type="radio" name="conf_content[]" value="0">关闭　
                   $a = explode(',',$v['field_value']);
//                    $a = [
//                        0=>'1|开启',
//                        1=>'0|关闭'
//                    ]
                    $str = '';
                    foreach ($a as $m=>$n){
//                        $n = '1|开启';
//                        $n = [
//                            0=>1,
//                            1=>'开启'
//                        ]
                        $aa = explode('|',$n);
//                        <input type="radio" name="conf_content[]" value="1">开启　
//                        判断此单选按钮是否被选中
                        $c = ($aa[0] == $data[$k]['conf_content'])?'checked':'';
                      $str.=   '<input  type="radio" name="conf_content[]" '.$c.' value="'.$aa[0].'">'.$aa[1];
                    }
                    $v['conf_contents'] = $str;
                    break;
            }
        }
        $title = "网站配置列表";
        return view('admin.config.index',compact('data','title'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        $title = '添加网站配置';
        return view('admin.config.create',compact('title'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(ConfigRequest $request)
    {
        //
        $data = $request->except('_token','field');

        $re = Config::create($data);

        

        // 调用putFile() 更新webconfig.php数据
        $this->putFile();

        if($re){
            return redirect('admin/config')->with('success','添加成功');
        }else{
            return back()->with('errors','添加失败');
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
        $title  ="网站配置修改";
        $data = Config::find($id);
        // dd($data);
        // dd($data);
        return view('admin.config.edit',compact('title','data'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(ConfigRequest $request, $id)
    {
        $data = $request -> except('_token','_method','field');
        // dd($data);
       
        $config = Config::find($id);
        // dd($config);
        if($request -> hasFile('field')){
            dd(11);
            $temp_name = md5(time()+rand(1000,9999));
            // 获取后缀
            $file = $request -> file('field');
            $hz = $file ->getClientOriginalExtension();
             // 文件路径
            $temp_path = 'uploads/'.date('Ymd',time()); 
            $temp = $temp_name.'.'.$hz;
            // 拼接文件名
            $name = ltrim($temp_path.'/'.$temp_name.'.'.$hz,'.');
            $temp_name2 = 'uploads/'.$temp_name.'.'.$hz;
            //文件上传
            // $request -> file('ppath') -> move($temp_path,$temp_name2);

            // 获取图片在临时文件中的地址
        
            $pic = $file->getRealPath();

            //阿里 OSS 图片上传
            $result = OSS::upload($temp_name2, $pic);
            
            // 修改
            // $config = Config::find($id);
            // dd($config);
            // 删除原来的图片
            // $dd = $config->conf_content;
            // $ossKey = 'uploads/'.$dd;
            // $aa = OSS::deleteObject($ossKey);
            // dd($dd);
            // $config->conf_title = $data['conf_title'];
            // $config->conf_name = $data['conf_name'];
            // $config->conf_content = $temp_name2;
            // $config->conf_tips = $data['conf_tips'];
            // $config->field_type = $data['field_type'];
            // $config->field_value = $data['field_value'];
            // $re = $config->save();


            

            $data['conf_content'] = $temp_name2;
            $re = $config -> update($data);
            // 调用putFile() 更新webconfig.php数据
            $this->putFile();


            // 判断
            if($re){
                return redirect('admin/config')->with('success','修改成功');
            }else{
                return back()->with('errors','修改失败');
            }
        }   
           

        
        
        $dd = Config::find($id);
        $re = $dd -> update($data);

        // 调用putFile() 更新webconfig.php数据
        $this->putFile();


        // 判断
        if($re){
            return redirect('admin/config')->with('success','修改成功');
        }else{
            return back()->with('errors','修改失败');
        }


    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        
        //获取要删除的数据
        $conf = Config::find($id);

        $data = [];
        $re = $conf -> delete();


         // 调用putFile() 更新webconfig.php数据
        $this->putFile();


        // 判断是否成功
        if($re){
            $data['status'] = 0;
            $data['msg'] = '删除成功';
        }else{
            $data['status'] = 1;
            $data['msg'] = '删除成功';
        }
        return $data;
    }
}
